package uestc.lj.gulishop.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import uestc.lj.common.exception.NoStockException;
import uestc.lj.common.to.OrderEntityTO;
import uestc.lj.common.to.StockDetailTO;
import uestc.lj.common.to.StockLockedTO;
import uestc.lj.common.utils.PageUtils;
import uestc.lj.common.utils.Query;
import uestc.lj.common.utils.R;
import uestc.lj.gulishop.ware.dao.WareSkuDao;
import uestc.lj.gulishop.ware.entity.WareOrderTaskDetailEntity;
import uestc.lj.gulishop.ware.entity.WareOrderTaskEntity;
import uestc.lj.gulishop.ware.entity.WareSkuEntity;
import uestc.lj.gulishop.ware.feign.OrderFeignService;
import uestc.lj.gulishop.ware.feign.ProductFeignService;
import uestc.lj.gulishop.ware.service.WareOrderTaskDetailService;
import uestc.lj.gulishop.ware.service.WareOrderTaskService;
import uestc.lj.gulishop.ware.service.WareSkuService;
import uestc.lj.gulishop.ware.vo.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author crazlee
 */
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    private WareSkuDao wareSkuDao;
    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private OrderFeignService orderFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(new Query<WareSkuEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>()
                .eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            try {
                R r = productFeignService.info(skuId);
                if (r.getCode() == 0) {
                    Map<String, Object> skuInfo = (Map<String, Object>) r.get("skuInfo");
                    String skuName = (String) skuInfo.get("skuName");
                    wareSkuEntity.setSkuName(skuName);
                }
            } catch (Exception e) {
                //若skuName未获取到，出现异常，自己catch掉不进行回滚
            }
            wareSkuDao.insert(wareSkuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVO> getSkuHasStock(List<Long> skuIds) {
        return skuIds.stream().map(skuId -> {
            SkuHasStockVO skuHasStockVO = new SkuHasStockVO();
            Long count = baseMapper.getSkuHasStock(skuId);
            skuHasStockVO.setSkuId(skuId);
            skuHasStockVO.setHasStock(count != null && count > 0);
            return skuHasStockVO;
        }).collect(Collectors.toList());
    }

    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean lockStocks(WareSkuLockVO skuLockVO) {
        // 保存库存工作单的详情---->追溯解锁库存
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(skuLockVO.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);
        // 1.寻找每个商品所在的仓库
        List<OrderItemVO> locks = skuLockVO.getLocks();
        List<SkuWareHasStock> skuWareHasStocks = locks.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setTitle(item.getTitle());
            skuWareHasStock.setNum(item.getCount());
            // 查询sku商品在哪里有库存
            List<Long> wareHasStockIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            skuWareHasStock.setWareId(wareHasStockIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());
        // 2.锁定库存
        Boolean allLocked = true;
        for (SkuWareHasStock skuWareHasStock : skuWareHasStocks) {
            Boolean skuStocked = false;
            Long skuId = skuWareHasStock.getSkuId();
            List<Long> wareIds = skuWareHasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                throw new NoStockException(skuId);
            }
            // 执行锁库存
            for (Long wareId : wareIds) {
                Long wareResult = wareSkuDao.lockSkuStock(skuId, wareId, skuWareHasStock.getNum());
                if (wareResult == 1) {
                    // 锁定成功,通知消息队列锁定成功
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null, skuId,
                            skuWareHasStock.getTitle(), skuWareHasStock.getNum(),
                            wareOrderTaskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);

                    StockLockedTO stockLockedTO = new StockLockedTO();
                    stockLockedTO.setId(wareOrderTaskEntity.getId());

                    // 锁失败时,只发id不行，防止回滚之后找不到数据
                    StockDetailTO stockDetailTO = new StockDetailTO();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockDetailTO);
                    stockLockedTO.setDetail(stockDetailTO);

                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTO);
                    skuStocked = true;
                    break;
                }
            }
            if (!skuStocked) {
                allLocked = false;
                throw new NoStockException(skuId);
            }
        }
        return allLocked;
    }

    /**
     * 处理延迟消息队列的方法（库存主动检查）
     *
     * @param to
     */
    @Override
    public void unLockStock(StockLockedTO to) {
        // 查询当前订单详情
        StockDetailTO detail = to.getDetail();
        Long detailId = detail.getId();
        // 解锁---->查询数据库关于这个订单的锁定库存信息
        WareOrderTaskDetailEntity entity = wareOrderTaskDetailService.getById(detailId);
        if (entity != null) {
            // 库存锁定成功
            Long id = to.getId();
            // 根据库存锁定单id查询库存锁定单实体
            WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getById(id);
            // 根据订单号查询订单的状态
            String orderSn = wareOrderTaskEntity.getOrderSn();
            R order = orderFeignService.getOrderStatus(orderSn);
            if (order.getCode() == 0) {
                // 远程订单数据状态查询成功
                OrderVO orderVO = order.getData(new TypeReference<OrderVO>() {
                });
                // 订单不存在或者订单状态是取消状态，解锁库存
                if (orderVO == null || orderVO.getStatus() == 4) {
                    // 订单是已锁定才解锁
                    if (entity.getLockStatus() == 1) {
                        releaseStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                throw new RuntimeException("远程查询订单状态失败！");
            }
        } else {
            // 无需解锁的
        }
    }

    /**
     * 处理库存延迟队列的方法（当订单释放之后，防止订单服务调用时间过长）
     *
     * @param orderEntityTO
     */
    @Override
    @Transactional
    public void unLockStock(OrderEntityTO orderEntityTO) {
        String orderSn = orderEntityTO.getOrderSn();
        // 查询库存的最新状态，防止重复解锁库存
        WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getOne(new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", orderSn));
        Long wareOrderTaskEntityId = wareOrderTaskEntity.getId();
        // 根据库存工作单找到没有解锁的库存
        List<WareOrderTaskDetailEntity> wareOrderTaskDetailEntities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", wareOrderTaskEntityId)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity wareOrderTaskDetailEntity : wareOrderTaskDetailEntities) {
            // 遍历解锁
            releaseStock(wareOrderTaskDetailEntity.getSkuId(), wareOrderTaskDetailEntity.getWareId(),
                    wareOrderTaskDetailEntity.getSkuNum(), wareOrderTaskDetailEntity.getId ());
        }
    }

    /**
     * 解锁库存
     *
     * @param skuId
     * @param wareId
     * @param num
     * @param taskDetailId
     */
    private void releaseStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        // 1.执行解锁
        wareSkuDao.releaseStock(skuId, wareId, num);
        // 2.更新库存状态单
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(taskDetailId);
        // 更新为已解锁
        wareOrderTaskDetailEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }

    /**
     * 解锁库存的方法
     * 1.查询数据库关于订单的锁定库存信息
     * 有-->库存锁定成功
     * 2.查询订单情况
     * 无-->创建订单失败，自己回滚，解锁
     * 有-->3. 判断订单的支付情况只有超时才会解锁
     * 无-->库存自己失败，已经回滚无需解锁
     *
     * @param to
     * @param message
     * @param channel
     * @throws IOException
     */
    public void handleStockLockedRelease(StockLockedTO to, Message message, Channel channel) throws IOException {

        System.out.println("收到解锁库存的消息");
        // 查询当前订单详情
        StockDetailTO detail = to.getDetail();
        Long detailId = detail.getId();
        // 解锁---->查询数据库关于这个订单的锁定库存信息
        WareOrderTaskDetailEntity entity = wareOrderTaskDetailService.getById(detailId);
        if (entity != null) {
            // 库存锁定成功
            Long id = to.getId();
            // 根据库存锁定单id查询库存锁定单实体
            WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getById(id);
            // 根据订单号查询订单的状态
            String orderSn = wareOrderTaskEntity.getOrderSn();
            R order = orderFeignService.getOrderStatus(orderSn);
            if (order.getCode() == 0) {
                // 远程订单数据状态查询成功
                OrderVO orderVO = order.getData(new TypeReference<OrderVO>() {
                });
                if (orderVO == null || orderVO.getStatus() == 4) {
                    // 订单不存在或者订单状态是取消状态，解锁库存
                    releaseStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                }
            } else {
                // 消息拒绝之后重新放回队列
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            }
        } else {
            // 无需解锁,库存锁定失败，自动回滚
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}